<template>
  <div class="tinymce-editor">
    <editor
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      :api-key="apiKey"
      @onClick="onClick"
      @onBlur="onBlur"
      @onFocus="onFocus"
    />
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
import tinymceConfig from '@/config/tinymce'
import axios from 'axios';  

export default {
  name: 'TinymceEditor',
  inject:['app'],
  components: {
    Editor
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      apiKey: 'ire0gxmc6etr2fzaw04xcp3u5cgpcnp7i7te51ydgng5cj1h',
      init: {
        // language_url:'./tinymce/langs/zh.CN.js',
        // language:'zh_CN',
        skin_url:'./tinymce/skins/ui/oxide',
        ...tinymceConfig.defaultConfig,
        images_upload_handler: function (blobInfo, success, failure) {
          let formData = new FormData();
          formData.append('file', blobInfo.blob(), blobInfo.filename());
          
          // 使用 axios 或其他 HTTP 客户端上传图片
          axios.post('/api/upload', formData)
            .then(res => {
              success(res.data.url);
            })
            .catch(err => {
              failure('图片上传失败：' + err.message);
            });
        },
        // 自定义按钮
        setup:(editor)=>{
           editor.ui.registry.addButton('imageUpload',{
            tooltip:'插入图片',
            icon:'image',
            onAction:()=>{
              this.app.chooseImage((data)=>{
                  // 插入到编辑器中
                  data.forEach(item=>{
                      editor.insertContent(`&nbsp;<img src="${item.url}">&nbsp;`)
                  })
                  
              },100)
            }
           })
        }
      }
    }
  },
  computed: {
    myValue: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    }
  },
  methods: {
    onClick(e) {
      this.$emit('onClick', e, this.myValue)
    },
    onBlur(e) {
      this.$emit('onBlur', e, this.myValue)
    },
    onFocus(e) {
      this.$emit('onFocus', e, this.myValue)
    }
  }
}
</script>

<style scoped>
.tinymce-editor {
  width: 100%;
  position: relative;
  z-index: 1;
}
</style> 